package cn.fl.system.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.system.condition.SysBkInfoQueryCondition;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.dto.SysBkInfoDTO;
import cn.fl.system.service.ISysBkInfoService;
import cn.fl.system.vo.SysBkInfoVO;
import net.sf.json.JSONArray;

/**
 * @Description: 银行信息表 控制层
 */
@Controller
@RequestMapping("/system/sysBkInfo")
public class SysBkInfoController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(SysBkInfoController.class);

	/**
	 * SysBkInfo 服务层BEAN
	 */
	@Autowired
	private ISysBkInfoService sysBkInfoService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toListPage", "加载银行列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysBkInfo/sysSysBkInfoList");
		return view;
	}
	
	/**
	 * 到银行账号页面
	 */
	@RequestMapping(value = "/toList.do", method = { RequestMethod.GET})
	public ModelAndView toList(HttpServletRequest request, HttpServletResponse response) {
		BaseLogUtils.info(logger, "toList", "跳转银行账号列表页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysBkInfo/sysSysBkAccList");
		return view;
	}

	/**
	 * 到修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		BaseLogUtils.info(logger, "toModifyPage", "加载银行修改页面.",CurrentThreadContext.getCurrentUserName());
		ModelAndView view = new ModelAndView("system/sysBkInfo/modify");
		view.addObject("id", id);
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initBkList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String bkNm = request.getParameter("bkNm");
		String bkNo = request.getParameter("bkNo");
		String sortName = request.getParameter("sortname");
		String sortOrder = request.getParameter("sortorder");
		
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(currentPage)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysBkInfoQueryCondition qc = new SysBkInfoQueryCondition();
		
		if (StringUtils.isNotEmpty(bkNm)) {
			qc.setBkNm(bkNm);
		}
		if (StringUtils.isNotEmpty(bkNo)) {
			qc.setBkNo(bkNo);
		}
		if(StringUtils.isNotEmpty(sortName) && StringUtils.isNotEmpty(sortOrder)){
			qc.setSortName(sortName);
			qc.setSortOrder(sortOrder);
		}
		page.setCondition(qc);

		BaseLogUtils.info(logger, "initBkList", "初始化银行列表页面数据.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		
		Pager pager = this.sysBkInfoService.searchListPage(page);
		List<SysBkInfoDTO> list = (List<SysBkInfoDTO>) pager.getResultList();
		ListPageVO<SysBkInfoDTO> listPage = new ListPageVO<SysBkInfoDTO>(list, pager.getTotalCount());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeByIds.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeBkById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String ids = request.getParameter("ids");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(ids)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "removeBkById", "删除银行数据,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		List<Long> idsList = new ArrayList<Long>();
		JSONArray idsArray = JSONArray.fromObject(ids);
		for (Object object : idsArray) {
			idsList.add(Long.valueOf(object.toString()));
		}
		
		try {
			boolean success = this.sysBkInfoService.removeByIds(idsList);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DELETE_FAIL);
				BaseLogUtils.info(logger, "removeBkById", "删除银行数据失败,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "removeBkById", "删除银行数据成功,ID:"+idsList.toString(), CurrentThreadContext.getCurrentUserName());
		} catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeBkById", "删除银行数据失败,ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		} catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeBkById", "删除银行数据失败,系统错误.ID:"+idsList.toString()+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getBkById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getBkById", "获取银行数据,主键参数为空！", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			SysBkInfoVO vo = this.sysBkInfoService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getBkById", "获取银行数据不存在,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getBkById", "获取银行数据成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getBkById", "获取银行数据失败,ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getBkById", "获取银行数据失败,系统错误.ID:"+id+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object addBk(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		SysBkInfoVO entity = new SysBkInfoVO();
		try {
			entity = this.getRequestParamForSysBkAdd(request);//获取参数
			Long id = this.sysBkInfoService.add(entity);
			result.setData(id);
			BaseLogUtils.info(logger, "addBk", "新增银行数据成功,ID:"+id+".DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "addBk", "新增银行数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "addBk", "新增银行数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyBk(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_UPDATE_SUCC);
		SysBkInfoVO entity = new SysBkInfoVO();
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyBk", "修改银行信息,主键参数为空！.ID:"+id, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		try {
			entity = this.getRequestParamForSysBkModify(request);
			entity.setId(Long.valueOf(id));
			boolean success = this.sysBkInfoService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_UPDATE_FAIL);
				BaseLogUtils.info(logger, "modifyBk", "修改银行数据失败.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modifyBk", "修改银行数据成功.DATA:"+JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modifyBk", "修改银行数据失败.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modifyBk", "修改银行数据失败,系统错误.DATA:"+JSONObject.toJSONString(entity)+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 启用银行
	 */
	@RequestMapping(value = "/enable.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object enableBk(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_ENABLE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "enableBk", "启用银行失败,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}

		try {
			
			boolean success = this.sysBkInfoService.enAbleSysBkInfo(Long.valueOf(id));
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_ENABLE_FAIL);
				BaseLogUtils.info(logger, "enableBk", "启用银行失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "enableBk", "启用银行成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "enableBk", "启用银行失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "enableBk", "启用银行失败,系统错误.ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	/**
	 * 禁用银行
	 */
	@RequestMapping(value = "/disable.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object disableBk(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES,SysLogConstant.LOG_CMM_DISABLE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "disableBk", "禁用银行,主键参数为空.", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			
			boolean success = this.sysBkInfoService.disAbleSysBkInfo(Long.valueOf(id));
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_DISABLE_FAIL);
				BaseLogUtils.info(logger, "disableBk", "禁用银行失败,ID:"+id, CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "disableBk", "禁用银行成功,ID:"+id, CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "disableBk", "禁用银行失败,ID:"+id+".ERROR:"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "disableBk", "禁用银行失败,系统错误.ID:"+id+".ERROR"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}	
	
	
	//********************私有方法********************//
	/**
	 * 获取银行参数信息
	 * @param request
	 * @return
	 * @throws BaseException
	 */
	private SysBkInfoVO getRequestParamForSysBk(HttpServletRequest request)throws BaseException{
		String bkLvlCd = request.getParameter("bkLvlCd");//银行级别(类型)
		String bkNm = request.getParameter("bkNm");//银行名称
		String bkNo = request.getParameter("bkNo");//行号
		String bkAddr = request.getParameter("bkAddr");//地址
		String bkPid1 = request.getParameter("bkPid");
		Long bkPid = null;//所属总行(父id)
		if (StringUtils.isNotBlank(bkPid1)&&!"".equals(bkPid1)) {
			bkPid = Long.parseLong(bkPid1);
		}
		String lmNm = request.getParameter("lmNm");//联系人
		String lmTel = request.getParameter("lmTel");//联系电话
		
		
		
		//验证必填项及长度
		if(StringUtils.isBlank(bkNm)){
			throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_604, "银行不能为空.");
		}
		
		if (StringUtils.isNotBlank(lmTel)) {
			if (!StringUtils.checkMobileNumber(lmTel)) {
				if (!StringUtils.isFixedPhone(lmTel)) {
					throw new BaseException(
							BaseExceptionConstant.BASE_EXCEPTION_CODE_604,
							"请输入正确的联系方式!");
				}
			}
		}
		SysBkInfoVO sysBkInfoVO = new SysBkInfoVO();
			sysBkInfoVO.setBkLvlCd(bkLvlCd.trim());
			sysBkInfoVO.setBkNm(bkNm.trim());
			sysBkInfoVO.setBkNo(bkNo.trim());
			sysBkInfoVO.setBkAddr(bkAddr.trim());
			sysBkInfoVO.setBkPid(bkPid);
			sysBkInfoVO.setLmNm(lmNm.trim());
			sysBkInfoVO.setLmTel(lmTel.trim());
		return sysBkInfoVO;
	}
	
	/**
	 * 获取银行请求参数(新增)
	 * @param request 请求
	 * @return 
	 */
	private SysBkInfoVO getRequestParamForSysBkAdd(HttpServletRequest request)throws BaseException{
		SysBkInfoVO sysBkInfoVO = this.getRequestParamForSysBk(request);
		sysBkInfoVO.setCrtTm(new Date());
		sysBkInfoVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
		return sysBkInfoVO;
	}
	
	/**
	 * 获取银行请求参数(修改)
	 * @param request 请求
	 * @return 
	 */
	private SysBkInfoVO getRequestParamForSysBkModify(HttpServletRequest request)throws BaseException{
		SysBkInfoVO sysBkInfoVO = this.getRequestParamForSysBk(request);
		sysBkInfoVO.setMdfTm(new Date());
		sysBkInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
		return sysBkInfoVO;
	}
}

